package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.pojo.CstService;
import com.ktjy.pojo.Customer;
import com.ktjy.pojo.Dict;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ICstServiceService;
import com.ktjy.service.ICustomerService;
import com.ktjy.service.IDictService;
import com.ktjy.service.ISysUserService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-01-16
 */
@Controller
@RequestMapping("/service")
public class CstServiceController {
    Logger logger = LoggerFactory.getLogger(CstServiceController.class);

    @Autowired
    ICstServiceService iCstServiceService;
    @Autowired
    IDictService iDictService;
    @Autowired
    ICustomerService iCustomerService;
    @Autowired
    ISysUserService iSysUserService;

    /**
     * 跳转到新增页面
     *
     * @return
     */
    @GetMapping("/add")
    public String add(Model model) {
        try {
            //查询客户信息
            List<Customer> customerList = iCustomerService.list();
            model.addAttribute("customerList", customerList);
            //查询服务类型
            QueryWrapper qw = new QueryWrapper();
            qw.eq("dict_type", "服务类型");
            List<Dict> typeList = iDictService.list(qw);
            model.addAttribute("typeList", typeList);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 add 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "service/add";
    }

    @PostMapping("/save")
    public String save(CstService cstService, HttpSession session) {
        //获取当前登录人
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        //设置服务创建人id
        cstService.setSvrCreateId(sysUser.getUsrId());
        //设置服务创建人名称
        cstService.setSvrCreateBy(sysUser.getUsrName());
        try {
            boolean ok = iCstServiceService.save(cstService);
            if (ok) {
                //跳转到列表;重定向到分页方法
                return "redirect:/service/dispatch";
            } else {
                //跳回新增页面
                return "redirect:/service/add";
            }
        } catch (Exception e) {
            logger.error("CstServiceController 中的 save 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 服务分配列表页面
     *
     * @param cstService
     * @param model
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/dispatch")
    public String dispatch(CstService cstService,
                           @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           HttpSession session,
                           Model model) {
        try {
            //组装分页条件
            Page<CstService> page = new Page<>(pageIndex, pageSize);

            //组装过滤条件 动态sql
            QueryWrapper<CstService> qw = new QueryWrapper();
            qw.eq("svr_status", "新创建");
            if (cstService.getSvrCustName() != null && !cstService.getSvrCustName().equals("")) {
                qw.like("svr_cust_name", cstService.getSvrCustName());
            }
            if (cstService.getSvrTitle() != null && !cstService.getSvrTitle().equals("")) {
                qw.like("svr_title", cstService.getSvrTitle());
            }
            if (cstService.getSvrType() != null && !cstService.getSvrType().equals("")) {
                qw.eq("svr_type", cstService.getSvrType());
            }
            //调用分页方法
            IPage<CstService> pager = iCstServiceService.page(page, qw);
            model.addAttribute("pager", pager);

            //查询条件回显
            model.addAttribute("condition", cstService);

            //查询服务类型
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "服务类型");
            List<Dict> typeList = iDictService.list(qw2);
            model.addAttribute("typeList", typeList);

            //查询所有角色为“客户经理”的用户
            QueryWrapper qw3 = new QueryWrapper();
            qw3.eq("usr_role_id", 2);
            List<SysUser> userList = iSysUserService.list(qw3);
            model.addAttribute("userList", userList);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 dispatch 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/dispatch_list";
    }

    /**
     * 保存服务分配信息
     *
     * @param cstService
     * @param session
     * @return
     */
    @PostMapping("/dispatch")
    @ResponseBody
    public Object dispatch(CstService cstService, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        //设置分配时间为当前时间
        cstService.setSvrDueDate(LocalDateTime.now());
        //设置服务状态为已分配
        cstService.setSvrStatus("已分配");
        try {
            boolean ok = iCstServiceService.updateById(cstService);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            logger.error("CstServiceController 中的 dispatch 方法执行发生错误。", e);
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 删除服务
     *
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok = iCstServiceService.removeById(id);  //调用service的方法进行数据删除
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            logger.error("LinkmanController 中的 del 方法执行发生错误。", e);
            map.put("delResult", false);
        }
        return map;
    }

    @GetMapping("/deal")
    public String deal(CstService cstService,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       HttpSession session,
                       Model model) {
        try {
            //组装分页条件
            Page<CstService> page = new Page<>(pageIndex, pageSize);

            //组装过滤条件 动态sql
            QueryWrapper<CstService> qw = new QueryWrapper();
            qw.eq("svr_status", "已分配");
            if (cstService.getSvrCustName() != null && !cstService.getSvrCustName().equals("")) {
                qw.like("svr_cust_name", cstService.getSvrCustName());
            }
            if (cstService.getSvrTitle() != null && !cstService.getSvrTitle().equals("")) {
                qw.like("svr_title", cstService.getSvrTitle());
            }
            if (cstService.getSvrType() != null && !cstService.getSvrType().equals("")) {
                qw.eq("svr_type", cstService.getSvrType());
            }
            //调用分页方法
            IPage<CstService> pager = iCstServiceService.page(page, qw);
            model.addAttribute("pager", pager);

            //查询条件回显
            model.addAttribute("condition", cstService);

            //查询服务类型
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "服务类型");
            List<Dict> typeList = iDictService.list(qw2);
            model.addAttribute("typeList", typeList);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 deal 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/deal_list";
    }

    /**
     * 跳转服务处理页面
     *
     * @param svrId
     * @param model
     * @return
     */
    @GetMapping("/toDeal")
    public String toDeal(Long svrId, Model model) {
        try {
            CstService cstService = iCstServiceService.getById(svrId);
            model.addAttribute("cstService", cstService);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 toDeal 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/deal";
    }

    /**
     * 保存服务处理信息
     *
     * @param cstService
     * @param session
     * @return
     */
    @PostMapping("/deal")
    public String deal(CstService cstService, HttpSession session) {
        try {
            //获取当前登录人
            SysUser loginUser = (SysUser) session.getAttribute("loginUser");
            //设置处理人id
            cstService.setSvrDealId(loginUser.getUsrId());
            //设置处理人姓名
            cstService.setSvrDealBy(loginUser.getUsrName());
            //设置处理时间为当前时间
            cstService.setSvrDealDate(LocalDateTime.now());
            //设置服务状态为已处理
            cstService.setSvrStatus("已处理");

            boolean ok = iCstServiceService.updateById(cstService);
            if (ok) {
                //跳转到列表;重定向到分页方法
                return "redirect:/service/deal";
            } else {
                //跳回新增页面
                return "redirect:/service/toDeal";
            }
        } catch (Exception e) {
            logger.error("CstServiceController 中的 deal 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 服务反馈列表页面
     *
     * @param cstService
     * @param model
     * @param pageIndex
     * @return
     */
    @GetMapping("/feedback")
    public String feedback(CstService cstService,
                           @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           HttpSession session,
                           Model model) {
        try {
            //组装分页条件
            Page<CstService> page = new Page<>(pageIndex, pageSize);

            //组装过滤条件 动态sql
            QueryWrapper<CstService> qw = new QueryWrapper();
            qw.eq("svr_status", "已处理");
            if (cstService.getSvrCustName() != null && !cstService.getSvrCustName().equals("")) {
                qw.like("svr_cust_name", cstService.getSvrCustName());
            }
            if (cstService.getSvrTitle() != null && !cstService.getSvrTitle().equals("")) {
                qw.like("svr_title", cstService.getSvrTitle());
            }
            if (cstService.getSvrType() != null && !cstService.getSvrType().equals("")) {
                qw.eq("svr_type", cstService.getSvrType());
            }
            //调用分页方法
            IPage<CstService> pager = iCstServiceService.page(page, qw);
            model.addAttribute("pager", pager);


            //查询条件回显
            model.addAttribute("condition", cstService);

            //查询服务类型
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "服务类型");
            List<Dict> typeList = iDictService.list(qw2);
            model.addAttribute("typeList", typeList);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 feedback 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/feedback_list";
    }

    /**
     * 跳转服务反馈页面
     *
     * @param svrId
     * @param model
     * @return
     */
    @GetMapping("/toFeedback")
    public String toFeedback(Long svrId, Model model) {
        try {
            CstService cstService = iCstServiceService.getById(svrId);
            model.addAttribute("cstService", cstService);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 feedback 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/feedback";
    }

    /**
     * 保存服务反馈信息
     *
     * @param cstService
     * @param session
     * @return
     */
    @PostMapping("/feedback")
    public String feedback(CstService cstService, HttpSession session) {
        try {
            //获取当前登录人
            SysUser loginUser = (SysUser) session.getAttribute("loginUser");
            //设置处理人id
            cstService.setSvrDealId(loginUser.getUsrId());
            //设置处理人姓名
            cstService.setSvrDealBy(loginUser.getUsrName());
            //设置处理时间为当前时间
            cstService.setSvrDealDate(LocalDateTime.now());
            if (cstService.getSvrSatisfy() >= 3) {
                //设置服务状态为已归档
                cstService.setSvrStatus("已归档");
            } else {
                //设置服务状态为已分配
                cstService.setSvrStatus("已分配");
            }
            boolean ok = iCstServiceService.updateById(cstService);
            if (ok) {
                return "redirect:/service/feedback";
            } else {
                return "redirect:/service/toFeedback";
            }
        } catch (Exception e) {
            logger.error("CstServiceController 中的 feedback 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 服务归档列表页面
     *
     * @param model
     * @param pageIndex
     * @return
     */
    @GetMapping("/arch")
    public String arch(CstService cstService,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       HttpSession session,
                       Model model) {
        try {
            //组装分页条件
            Page<CstService> page = new Page<>(pageIndex, pageSize);

            //组装过滤条件 动态sql
            QueryWrapper<CstService> qw = new QueryWrapper();
            qw.eq("svr_status", "已归档");
            if (cstService.getSvrCustName() != null && !cstService.getSvrCustName().equals("")) {
                qw.like("svr_cust_name", cstService.getSvrCustName());
            }
            if (cstService.getSvrTitle() != null && !cstService.getSvrTitle().equals("")) {
                qw.like("svr_title", cstService.getSvrTitle());
            }
            if (cstService.getSvrType() != null && !cstService.getSvrType().equals("")) {
                qw.eq("svr_type", cstService.getSvrType());
            }
            //调用分页方法
            IPage<CstService> pager = iCstServiceService.page(page, qw);
            model.addAttribute("pager", pager);
            //查询条件回显
            model.addAttribute("condition", cstService);
            //查询服务类型
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "服务类型");
            List<Dict> typeList = iDictService.list(qw2);
            model.addAttribute("typeList", typeList);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 arch 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/arch_list";
    }

    /**
     * 跳转归档服务查看页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view")
    public String view(@RequestParam("id") Long id, Model model) {
        try {
            CstService cstService = iCstServiceService.getById(id);
            model.addAttribute("cstService", cstService);
        } catch (Exception e) {
            logger.error("CstServiceController 中的 view 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "service/view";
    }

}
